//
//  YLPasteBoardChecker.swift
//  YLIMKeyBoard
//
//  Created by AlbertYuan on 2023/2/6.
//  剪切板信息检测工具
/**
 1.获取剪切板内容

 2.向服务器验证剪切板内容是否合规（此内容必须符合某种规定才提交服务验证，避免过度资源开销【拾光家】url xxxxxxx）

 3.合规数据执行弹窗显示，并删除数据信息（防止重复验证）

 */
import UIKit
import RxSwift
import RxCocoa
import NSObject_Rx

//剪切板数据类型处理
public enum YLPasteBoardCheckType{

    case string //字符串

    case strings //字符串数组

    case image  //图片

    case data //二进制数据
}

public class YLPasteBoardChecker: NSObject {
    //clear：服务器验证后清空操作
    public typealias  closeClousure = (()->Void)
    
    public var currentShare : String?
    //剪切板数据:元祖第一个元素为符合条件的字符串；第二个元素为关闭回调
    public var pasteboardState = BehaviorRelay<(content:String,closeClousure:closeClousure)>(value: ("",{}))
    //内部检测标准
    public static var cheakStandard:String = "【拾光家】"

    public static let share = YLPasteBoardChecker()
    private override init() {
        super.init()

        //初次初始化就开始检测
        getPasteboardInfomation()
        //每次前台打开检测前台监听
        NotificationCenter.default.rx.notification(UIApplication.didBecomeActiveNotification)
            .subscribe {[weak self] Notification in
                guard let `self` = self else { return }
                self.getPasteboardInfomation()
        }.disposed(by: rx.disposeBag)
        
    }

    /// 获取剪切板内容
    /// - Parameter checkStandard: 内部验证标准，需要时传递
    public func getPasteboardInfomation(checkStandard:String? = nil){
        //校验标准设置
        var checkS:String =  YLPasteBoardChecker.cheakStandard
        if let checkStandard = checkStandard{
            checkS = checkStandard
        }
        var content : String?
        let board = UIPasteboard.general
        
        if #available(iOS 16.0, *) {
            
            
            board.detectPatterns(for: [.probableWebSearch,.probableWebURL,.number], completionHandler: {result in
                switch result {
                case .success(let set):
                    var hasWeb = false
                    for type in set {
                        if type == .probableWebURL {
                            hasWeb = true
                        }
                    }
                    
                    if hasWeb {
                        self.checkPasetboardInfo()
                    }
                    
                case .failure(_):
                    break
                }
            })
        } else {
            // Fallback on earlier versions
            self.checkPasetboardInfo()
        }

    }

    private func checkPasetboardInfo() {
        let pas = UIPasteboard.general
        var conntent : String?
        let pasStr = pas.string
        conntent = pasStr

        if let conntent = conntent {
            pasteboardState.accept((conntent, {self.clearPasteboard()}))
        }
    }
    
    /// 获取剪切板内容
    /// - Returns: 内容信息
    private  func getPasetboardInfo(checkType:YLPasteBoardCheckType? = .string) -> Any?{
        let pas = UIPasteboard.general
        switch checkType{
        case .string:
            if (pas.hasStrings) {
                if (pas.string ?? "").hasPrefix("【拾光家】") {
                    return pas.string
                }
            }
        case .strings:
            if (pas.hasStrings ) {
                return pas.strings
            }
        case .image:
            if (pas.hasImages ) {
                return pas.image
            }
        default:
            return pas.data(forPasteboardType: "pasteboard.png")
        }
        return nil
    }

    /// 清空剪贴板内容
    private func clearPasteboard(){
        let pas = UIPasteboard.general
        pas.string = ""
        debugPrint("执行粘贴板清除完成")
    }

}
